package com.example.jdk8.threads;

import java.util.concurrent.*;

public class ThreadTimeOut {
    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        // 初始化线程池
        ExecutorService executor = Executors.newFixedThreadPool(1);
        // 创建线程任务
        Future<Integer> future = executor.submit(() -> {
            try {
                // 睡眠2s
                TimeUnit.SECONDS.sleep(2);
                return 123;
            } catch (InterruptedException e) {
                throw new IllegalStateException("task interrupted", e);
            }
        });
        // 1s 就需要返回结果
        future.get(1, TimeUnit.SECONDS);
        /*
        结果：
        Exception in thread "main" java.util.concurrent.TimeoutException
	at java.util.concurrent.FutureTask.get(FutureTask.java:205)
	at com.example.jdk8.threads.ThreadTimeOut.main(ThreadTimeOut.java:18)
         */
    }
}
